package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetMealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private SetMealMapper setMealMapper;

    @Override
    public void save(Category category) {
        categoryMapper.save(category);
    }

    @Override
    public Page<Category> findByPage(int pageNum, int pageSize) {
        //设置页面大小和页面数据
        PageHelper.startPage(pageNum,pageSize);
        //查询数据
        List<Category> categoryList = categoryMapper.findByPage();
        //创建PageInfo对象
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        //创建Page对象
        Page<Category> page = new Page<>(pageInfo.getList(),pageInfo.getTotal(),pageSize,pageNum);
        return page;
    }

    @Override
    public void delete(Long id) {
        Long count = dishMapper.findDishByCategory(id);
        if (count > 0){
            throw  new CustomException("关联其他菜品，无法删除");
        }
        count = setMealMapper.findSetMealByCategory(id);
        if (count > 0){
            throw  new CustomException("关联其他套餐，无法删除");
        }
        categoryMapper.delete(id);
    }

    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }


}
